package com.lagou.edu.user.controller;

import com.lagou.edu.user.client.CodeClient;
import com.lagou.edu.user.entity.UserDO;
import com.lagou.edu.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liangzj
 * @date 2021/6/23 21:54
 */
@CrossOrigin(originPatterns = "*", allowedHeaders = "*", allowCredentials = "true", methods = {RequestMethod.GET, RequestMethod.POST})
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CodeClient codeClient;

    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable String email,
                            @PathVariable String password,
                            @PathVariable String code) {
        if (codeClient.validate(email, code)) {
            return false;
        }

        return userService.addUser(email, password);
    }

    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email) {
        return userService.existEmail(email);
    }

    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable String email,
                        @PathVariable String password,
                        HttpServletResponse response) {
        UserDO userDO = userService.getUser(email, password);
        Assert.notNull(userDO, "用户名或密码错误！");

        String token = userService.createToken(userDO.getEmail());

        Cookie cookie = new Cookie("authToken", token);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        cookie.setDomain("localhost");
        response.addCookie(cookie);

        return email;
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable String token) {
        return userService.getUser(token).getEmail();
    }
}
